package com.meggie.media;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaDescription;
import android.media.MediaMetadata;
import android.media.browse.MediaBrowser;
import android.media.session.MediaController;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";
    private TextView tvMusicName;
    private TextView tvMusicArtist;
    private TextView tvMusicAlbum;
    private TextView tvBlueDeviceName;
    private ImageView imgPlayOrPause;
    private Context mContext;

    private BluetoothAdapter bluetoothAdapter;
    private MediaBrowser mMediaBrowser;
    private MediaController mMediaController;
    private int playState = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        ActivityCompat.requestPermissions(this, new String[]{
                "android.permission.BLUETOOTH_SCAN",
                "android.permission.BLUETOOTH_ADVERTISE",
                "android.permission.BLUETOOTH_CONNECT",
                "android.permission.BLUETOOTH",
                "android.permission.BLUETOOTH_ADMIN"

        }, 1);
        tvMusicName = (TextView) findViewById(R.id.tv_music_name);
        tvMusicArtist = (TextView) findViewById(R.id.tv_music_artist);
        tvMusicAlbum = (TextView) findViewById(R.id.tv_music_album);
        imgPlayOrPause = (ImageView) findViewById(R.id.m_img_play);
        tvBlueDeviceName = (TextView) findViewById(R.id.tv_bluetooth_device);

        Log.e(TAG, "蓝牙连接广播监听");
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(bluetoothReceiver, filter);

        connectBluetoothDevice();


    }


    /**
     * 蓝牙连接状态广播监听
     */
    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "bluetoothReceiver action:" + action);
            if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
                Log.e("bluetooth", "BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED");
            }
            int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0);
            switch (bluetoothState) {
                case BluetoothAdapter.STATE_CONNECTED://蓝牙连接
                    Log.i("bluetooth", "STATE_CONNECTED  mMediaBrowser" + mMediaBrowser);
                    if (mMediaBrowser == null || (mMediaBrowser != null && !mMediaBrowser.isConnected())) {
                        connectMediaBrowser();
                    }
                    break;
                case BluetoothAdapter.STATE_CONNECTING:
                    Log.i("bluetooth", "STATE_CONNECTING");
                    break;
                case BluetoothAdapter.STATE_DISCONNECTED://断开蓝牙连接
                    Log.i("bluetooth", "STATE_DISCONNECTED  mMediaBrowser:" + mMediaBrowser);
                    if (mMediaBrowser != null) {
                        mMediaBrowser.disconnect();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateMediaPlayerInfo(null);
                            imgPlayOrPause.setImageResource(R.drawable.icon_pause);
                            tvBlueDeviceName.setText(getString(R.string.str_bluetooth_device) + "Null");
                        }
                    });
                    Toast.makeText(mContext, "请连接蓝牙", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothAdapter.STATE_DISCONNECTING:
                    Log.i("bluetooth", "STATE_DISCONNECTING");
                    break;
                default:
                    Log.i("bluetooth", "DEFAULT");
                    break;
            }

        }
    };


    /**
     * 检查是否有蓝牙设备连接成功，并绑定媒体浏览器服务
     */
    private void connectBluetoothDevice() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            Toast.makeText(mContext, "该设备不支持蓝牙连接", Toast.LENGTH_SHORT).show();
            return;
        }
        //如果蓝牙当前已启用并可供使用，则返回 true
        if (!bluetoothAdapter.isEnabled()) {
            // 请求打开蓝牙
            Toast.makeText(mContext, "请求打开蓝牙", Toast.LENGTH_SHORT).show();
        } else {
            boolean isBtConnect = isBTConnected();//是否有设备连接
            if (isBtConnect) {//有设备连接后绑定媒体浏览器服务
                connectMediaBrowser();
            } else {
                tvBlueDeviceName.setText(getString(R.string.str_bluetooth_device) + "Null");
                Toast.makeText(mContext, "请连接蓝牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 是否有设备连接蓝牙
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public boolean isBTConnected() {
        try {
            Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            method.setAccessible(true);
            int state = (int) method.invoke(bluetoothAdapter, (Object[]) null);
            Log.e(TAG, "state===" + state); //注意：已连接蓝牙后但state仍然为0的情况下需要检查是否有权限，Android10以上设备需要动态申请权限
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Log.i(TAG, "BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();//注意要在AndroidManifest中配置权限
                Log.i(TAG, "devices:" + devices.size());

                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if (isConnected) {
                        Log.i(TAG, "connected:" + device.getAddress());
                        tvBlueDeviceName.setText(getString(R.string.str_bluetooth_device) + device.getName());
                    }
                }
                return true;
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return false;
    }


    /**
     * 连接媒体浏览器服务
     * 1、android-7（N版本） ~ android-9（P版本）：
     * String package = "com.android.bluetooth"；
     * String class = "com.android.bluetooth.a2dpsink.mbs.A2dpMediaBrowserService"
     * <p>
     * 2、Android10以上的版本服务包名和文件名分别为：
     * String package = "com.android.bluetooth"；
     * String class = "com.android.bluetooth.avrcpcontroller.BluetoothMediaBrowserService"
     */
    private void connectMediaBrowser() {
        //1.绑定服务，Android10以上的版本服务名称为
        ComponentName componentName = new ComponentName("com.android.bluetooth", "com.android.bluetooth.avrcpcontroller.BluetoothMediaBrowserService");
        // 2.创建MediaBrowser
        mMediaBrowser = new MediaBrowser(this, componentName, connectionCallback, null);
        //3.连接MediaBrowser
        mMediaBrowser.connect();
    }


    private MediaBrowser.ConnectionCallback connectionCallback = new MediaBrowser.ConnectionCallback() {
        public void onConnected() {
            //如果服务端接受连接，就会调此方法表示连接成功，否则回调onConnectionFailed();
            Log.d(TAG, "onConnected: ");
            //获取配对令牌
            MediaSession.Token token = mMediaBrowser.getSessionToken();
            //通过token，获取MediaController,第一个参数是context，第二个参数为token
            mMediaController = new MediaController(mContext, token);
            Log.e(TAG, "mMediaController===" + mMediaController);
            //mediaController注册回调，callback就是媒体信息改变后，服务给客户端的回调
            mMediaController.registerCallback(mMediaCallBack);
        }

        public void onConnectionSuspended() {
            Log.d(TAG, "onConnectionSuspended: ");
            //与服务断开回调（可选）
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateMediaPlayerInfo(null);
                    imgPlayOrPause.setImageResource(R.drawable.icon_pause);
                }
            });
            playState = 0;
        }

        public void onConnectionFailed() {
            Log.d(TAG, "onConnectionFailed: ");
            //连接失败回调（可选）
            updateMediaPlayerInfo(null);
        }
    };

    private MediaController.Callback mMediaCallBack = new MediaController.Callback() {
        @Override
        public void onMetadataChanged(@Nullable MediaMetadata metadata) {
            super.onMetadataChanged(metadata);
            Log.e(TAG, "onMetadataChanged  metadata===" + metadata + "  Thread===" + Thread.currentThread().getName());
            if (metadata != null) {
                MediaDescription description = metadata.getDescription();
                //加此判断是为了避免重复更新UI
                if (!tvMusicName.getText().equals(description.getTitle()) || !tvMusicArtist.getText().equals(description.getSubtitle()) || !tvMusicAlbum.getText().equals(description.getDescription()))
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateMediaPlayerInfo(description);
                        }
                    });
            }
        }

        @Override
        public void onPlaybackStateChanged(@Nullable PlaybackState state) {
            super.onPlaybackStateChanged(state);
            //播放状态信息回调，更新。PlaybackState在文章后面会提及
            Log.e(TAG, "onPlaybackStateChanged state:" + state + "  Thread===" + Thread.currentThread().getName());
//            //获取当前播放进度
//            long position = state.getPosition();
            if (state != null) {
                if (state.getState() != playState)
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatePlayState(state);
                        }
                    });
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
    }

    public void onBaseClick(View view) {
        switch (view.getId()) {
            case R.id.m_img_prev:
                if (mMediaController != null)
                    mMediaController.getTransportControls().skipToPrevious();
                break;
            case R.id.m_img_next:
                if (mMediaController != null)
                    mMediaController.getTransportControls().skipToNext();
                break;
            case R.id.m_img_play:
                if (mMediaController != null) {
                    handlerPlayEvent();
                }
                break;
        }
    }

    private void handlerPlayEvent() {
        switch (mMediaController.getPlaybackState().getState()) {
            case PlaybackState.STATE_PLAYING:
                Log.e(TAG, "handlerPlayEvent getPlaybackState  STATE_PLAYING:");
                mMediaController.getTransportControls().pause();
                break;
            case PlaybackState.STATE_PAUSED:
                Log.e(TAG, "handlerPlayEvent getPlaybackState  STATE_PAUSED:");
                mMediaController.getTransportControls().play();
                break;
            default:
                Log.e(TAG, "handlerPlayEvent getPlaybackState  playFromSearch:");
                mMediaController.getTransportControls().playFromSearch("", null);
                break;
        }
    }

    private void updateMediaPlayerInfo(MediaDescription description) {
        Log.d(TAG, "updateMediaPlayerInfo ..description:" + description);
        if (null != description) {
            Log.e(TAG, "description.getTitle():" + description.getTitle() + "  getSubtitle:" + description.getSubtitle() + "  getDescription:" + description.getDescription());
            tvMusicName.setText("" + (TextUtils.isEmpty(description.getTitle()) ? getString(R.string.unknown_song) : description.getTitle()));
            tvMusicArtist.setText("" + (TextUtils.isEmpty(description.getSubtitle()) ? getString(R.string.unknown_artist) : description.getSubtitle()));
            tvMusicAlbum.setText("" + (TextUtils.isEmpty(description.getDescription()) ? getString(R.string.unknown_album) : description.getDescription()));
        } else {
            tvMusicName.setText("" + (getString(R.string.unknown_song)));
            tvMusicArtist.setText("" + getString(R.string.unknown_artist));
            tvMusicAlbum.setText("" + getString(R.string.unknown_album));
        }

    }

    private void updatePlayState(PlaybackState state) {
        if (state == null) {
            return;
        }
        Log.e(TAG, "updatePlayState getState:" + state.getState());
        switch (state.getState()) {
            case PlaybackState.STATE_NONE://无任何状态
                imgPlayOrPause.setImageResource(R.drawable.icon_pause);
                playState = 0;
            case PlaybackState.STATE_PAUSED:
                imgPlayOrPause.setImageResource(R.drawable.icon_pause);
                playState = 2;
                break;
            case PlaybackState.STATE_PLAYING:
                imgPlayOrPause.setImageResource(R.drawable.icon_play);
                playState = 3;
                break;
        }
    }

}